package com.example.google_map_test;


import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.widget.TextView;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;



public class ADD extends Activity  implements LocationListener{
	OnClickListener	backClick	= null;	
	OnClickListener listener_add = null;
	Button button_add;
	DBConnection helper;
	public int id_this;
	
	
	

	
	
	private static final int IMAGE_CAPTURE = 0; 
    private Button startBtn; 
    private Uri imageUri; 
    private ImageView imageView; 
	
	
	
	
	
	public interface UserSchema {
			String TABLE_NAME = "Users";          //Table Name
			String ID = "_id";                    //ID
			String USER_NAME = "user_name";       //User Name
			String ADDRESS = "address";           //Address
			String TELEPHONE = "telephone";       //Phone Number
			String MAIL_ADDRESS = "mail_address"; //Mail Address
			String PHOTO_ADDRESS = "photo_address";
		}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);
        
    	
        
        
      //取得系統定位服務
      		LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE));
      		locationServiceInitial();
      		if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
      			//如果GPS或網路定位開啟，呼叫locationServiceInitial()更新位置
      			getService = true;	//確認開啟定位服務
      			locationServiceInitial();
      		} else {
      			//Toast.makeText(this, "請開啟定位服務", Toast.LENGTH_LONG).show();
      			
      		}
        

        
        TextView mTextView08 = (TextView)findViewById(R.id.TextView08);  	
    	mTextView08.setText("Location-GPS");
        
    	
    	

        
        //imageView = (ImageView)findViewById(R.id.img); 
        startBtn = (Button) findViewById(R.id.startBtn); 
        startBtn.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                startCamera(); 
            } 
        }); 
        
        
        
        
      //找尋Button按鈕
        Button button = (Button)findViewById(R.id.choosebutton);
        //設定按鈕內文字
        button.setText("選擇圖片");
        //設定按鈕監聽式
        button.setOnClickListener(new Button.OnClickListener(){
      public void onClick(View v) {
        Intent intent = new Intent();
        //開啟Pictures畫面Type設定為image
           intent.setType("image/*");
            //使用Intent.ACTION_GET_CONTENT這個Action                                            //會開啟選取圖檔視窗讓您選取手機內圖檔
            intent.setAction(Intent.ACTION_GET_CONTENT); 
        //取得相片後返回本畫面
            startActivityForResult(intent, 1);
      }
             
        });
        
        
        
        
        final EditText mEditText01 = (EditText)findViewById(R.id.EditText01);
        final EditText mEditText02= (EditText)findViewById(R.id.EditText02);
		final EditText mEditText03 = (EditText)findViewById(R.id.EditText03);
		final EditText mEditText04 = (EditText)findViewById(R.id.EditText04);
		final EditText mEditText05 = (EditText)findViewById(R.id.EditText05);
		
		
//		
//		
//		Intent intent=getIntent(); 
//        String Latitude=intent.getStringExtra("Latitude"); 
//        String Longitude=intent.getStringExtra("Longitude"); 
//		
		
		Bundle Data = this.getIntent().getExtras();
	      
	      // 取得 Bundle 中的資料
	    Double Latitude = Data.getDouble("Latitude");
	    Double Longitude = Data.getDouble("Longitude");		            
	    mEditText02.setText(String.valueOf(Latitude));
	    mEditText03.setText(String.valueOf(Longitude));
		
		
		//建立資料庫PhoneBookDB和表單Table:Users
		helper = new DBConnection(this);
        final SQLiteDatabase db = helper.getWritableDatabase();	
        final String[] FROM = 
		{   
        	UserSchema.ID,
        	UserSchema.USER_NAME,
        	UserSchema.TELEPHONE,
        	UserSchema.ADDRESS, 
        	UserSchema.MAIL_ADDRESS,
        	UserSchema.PHOTO_ADDRESS
		};
        //取得所有資料的USER_NAME，安置在list[]上
        Cursor c = db.query(UserSchema.TABLE_NAME, new String[] {UserSchema.USER_NAME}, null, null, null, null, null);
		c.moveToFirst();
		CharSequence[] list = new CharSequence[c.getCount()];
		for (int i = 0; i < list.length; i++) {
				list[i] = c.getString(0);
				c.moveToNext();
		}
		c.close();
		
		
		
//		
//		//顯示USER_NAME在Spinner表單-spinner上
//		Spinner spinner = (Spinner)findViewById(R.id.Spinner01);
//		spinner.setAdapter(new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, list));
//		//在Spinner表單-spinner上選定查詢資料，顯示所有資料在畫面上
//		spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
//			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//				String user_name = ((Spinner)parent).getSelectedItem().toString();
//				Cursor c = db.query("Users", FROM , "user_name='" + user_name + "'", null, null, null, null);
//				c.moveToFirst();
//				id_this = Integer.parseInt(c.getString(0));
//				String user_name_this = c.getString(1);
//				String telephone_this = c.getString(2);
//				String address_this = c.getString(3);
//				String mail_address_this = c.getString(4);
//				String photo_address_this = c.getString(5);
//				c.close();
//				mEditText01.setText(user_name_this);
//				mEditText02.setText(telephone_this);
//				mEditText03.setText(address_this);
//				mEditText04.setText(mail_address_this);
//				mEditText05.setText(photo_address_this);
//				
//			}
//			public void onNothingSelected(AdapterView<?> parent) {
//			}
//		});    
		

		
        //按下[Add]按鈕時，新增一筆資料
        listener_add = new OnClickListener() {	
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				values.put(UserSchema.USER_NAME, mEditText01.getText().toString());
				values.put(UserSchema.TELEPHONE, mEditText02.getText().toString());
				values.put(UserSchema.ADDRESS, mEditText03.getText().toString());
				values.put(UserSchema.MAIL_ADDRESS, mEditText04.getText().toString());
				values.put(UserSchema.PHOTO_ADDRESS, mEditText05.getText().toString());
				SQLiteDatabase db = helper.getWritableDatabase();
				db.insert(UserSchema.TABLE_NAME, null, values);
				db.close();
				//onCreate(savedInstanceState);
				Intent intent3=new Intent();
				intent3.setClass(ADD.this,MainActivity.class);
				startActivity(intent3);
			}
		};
		
		//設定BUTTON0i,i=1,2,3,4的OnClickListener
		button_add = (Button)findViewById(R.id.Button01);
		button_add.setOnClickListener(listener_add);   
		
		
		backClick = new OnClickListener()
        {
        	public void onClick(View v) 
			{
				Intent intent3=new Intent();
				intent3.setClass(ADD.this,MainActivity.class);
				startActivity(intent3);

			}
        };
        
        
        Button backBtn=(Button)findViewById(R.id.Button05);
        backBtn.setOnClickListener(backClick);
		
		
		
    }
    
    private boolean getService = false;
    private String bestProvider = LocationManager.GPS_PROVIDER;
    private LocationManager lms;
	private void locationServiceInitial() {
		lms = (LocationManager) getSystemService(LOCATION_SERVICE);	//取得系統定位服務
		Criteria criteria = new Criteria();	//資訊提供者選取標準
		bestProvider = lms.getBestProvider(criteria, true);	//選擇精準度最高的提供者
		Location location = lms.getLastKnownLocation(LocationManager.GPS_PROVIDER);	//使用GPS定位座標
		getLocation(location);
	}
	private void getLocation(Location location) {	//將定位資訊顯示在畫面中
		if(location != null) {
		
			TextView mTextView01 = (TextView)findViewById(R.id.TextView01);
	    	TextView mTextView02 = (TextView)findViewById(R.id.TextView02);
	    	TextView mTextView03 = (TextView)findViewById(R.id.TextView03);
	    	mTextView01.setText("緯度-Latitude：  " + String.valueOf(location.getLatitude()));
	    	mTextView02.setText("經度-Longitude：  " + String.valueOf(location.getLongitude()));
	    	mTextView03.setText("標高-Latitude：  " + String.valueOf(location.getAltitude()));
	    	

//	    	EditText mEditText_Latitude= (EditText)findViewById(R.id.EditText02);
//	    	EditText mEditText_Longitude= (EditText)findViewById(R.id.EditText03);
//
//	    	mEditText_Latitude.setText(String.valueOf(location.getLatitude()));
//	    	mEditText_Longitude.setText(String.valueOf(location.getLongitude()));

			
			
		}
		else {
			//Toast.makeText(this, "無法定位座標", Toast.LENGTH_LONG).show();
		}
	}
    
    
    
    
    
    
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(getService) {
			lms.requestLocationUpdates(bestProvider, 1000, 1, this);
			//服務提供者、更新頻率60000毫秒=1分鐘、最短距離、地點改變時呼叫物件
		}
	}
 
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(getService) {
			lms.removeUpdates(this);	//離開頁面時停止更新
		}
	}
	
	
	public void onLocationChanged(Location location) {	//當地點改變時
		// TODO Auto-generated method stub
		getLocation(location);
	}

    


    
    
    
    public void startCamera() { 
        Log.d("ANDRO_CAMERA", "Starting camera on the phone..."); 
        String fileName = "testphoto.jpg"; 
        ContentValues values = new ContentValues(); 
        values.put(MediaStore.Images.Media.TITLE, fileName); 
        values.put(MediaStore.Images.Media.DESCRIPTION, 
                "Image capture by camera"); 
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());//图像的拍摄时间，显示时根据这个排序
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); 
        imageUri = getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 
        startActivityForResult(intent, IMAGE_CAPTURE); 
        
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    	super.onActivityResult(requestCode, resultCode, data);
    	if (requestCode == IMAGE_CAPTURE) { 
            if (resultCode == RESULT_OK){ 
                Log.d("ANDRO_CAMERA","Picture taken!!!");
                imageView = (ImageView)findViewById(R.id.img); 
                imageView.setImageURI(imageUri); 
            	ContentResolver cr = this.getContentResolver();
            	Cursor cursor = cr.query(imageUri, null, null, null, null);
            	cursor.moveToFirst();
            	if (cursor != null) {
            	        String path = cursor.getString(1);
            	        Log.e("path="+path, path); //这个就是我们想要的原图的路径
            	        Toast.makeText(this, "path="+ path, Toast.LENGTH_LONG).show();
            	        cursor.close();
            	        EditText mEditText_Text= (EditText)findViewById(R.id.EditText05);
            	        mEditText_Text.setText(String.valueOf(path));
            	}
            }
               
        }
    	else  {
    		if (resultCode == RESULT_OK) {
	                //取得圖檔的路徑位置
	                Uri uri = data.getData();
	                //寫log
	                Log.e("uri", uri.toString());
	                //抽象資料的接口
	                ContentResolver cr = this.getContentResolver();
	              try {
	                //由抽象資料接口轉換圖檔路徑為Bitmap
	                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
	                //取得圖片控制項ImageView
	                ImageView imageView = (ImageView) findViewById(R.id.img);
	                // 將Bitmap設定到ImageView
	                imageView.setImageBitmap(bitmap);
	               } catch (FileNotFoundException e) {
	                 Log.e("Exception", e.getMessage(),e);
	               }
	              
	              
	              String [] proj={MediaStore.Images.Media.DATA};
	              Cursor cursor = managedQuery( uri,
	                              proj, // Which columns to return
	
	                              null, // WHERE clause; which rows to return (all rows)
	
	                              null, // WHERE clause selection arguments (none)
	
	                              null); // Order-by clause (ascending by name)
	
	              
	             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	              cursor.moveToFirst();
	              String path =cursor.getString(column_index);
	              Log.e("path="+path, path); //这个就是我们想要的原图的路径
	  	        Toast.makeText(this, "path="+ path, Toast.LENGTH_LONG).show();
	              EditText mEditText_Text= (EditText)findViewById(R.id.EditText05);
	  	          mEditText_Text.setText(String.valueOf(path));
             }
               
    	}
    }


    
    
    
    
    
    public static class DBConnection extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "PhoneBookDB";
		private static final int DATABASE_VERSION = 1;
		private DBConnection(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}
		public void onCreate(SQLiteDatabase db) {
			String sql = "CREATE TABLE " + UserSchema.TABLE_NAME + " (" 
			+ UserSchema.ID  + " INTEGER primary key autoincrement, " 
			+ UserSchema.USER_NAME + " text not null, " 
			+ UserSchema.TELEPHONE + " text not null, " 
			+ UserSchema.ADDRESS + " text not null, "
			+ UserSchema.MAIL_ADDRESS + " text not null, "
			+ UserSchema.PHOTO_ADDRESS + " text not null "+ ");";
			//Log.i("haiyang:createDB=", sql);
			db.execSQL(sql);	
		}
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub	
		}
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}   
}